const UserModel = require("../../models/UserModel");
const UserService = {
  login: async ({ username, password }) => {
    const user = await UserModel.findOne({ username });

    if (!user) {
      return []; // 用户不存在
    }

    const isMatch = await user.comparePassword(password);

    if (isMatch) {
      return [user]; // 密码匹配，返回用户数据
    } else {
      return []; // 密码不匹配
    }
  },

  upload: async ({ _id, username, introduction, gender, avatar }) => {
    const update = {
      username,
      introduction,
      gender,
    };
    if (avatar) update.avatar = avatar;
    return await UserModel.updateOne({ _id }, update);
  },

  add: async ({ username, password, role, gender, introduction, avatar }) => {
    return await UserModel.create({
      username,
      password,
      role,
      gender,
      introduction,
      avatar,
    });
  },

  getListById: async ({ id }) => {
    let data = ["_id", "username", "role", "gender", "introduction", "avatar"];
    return id
      ? UserModel.find({ _id: id }, [...data])
      : UserModel.find({}, [...data]);
  },

  getListOfPage: async ({
    searchValue,
    pageNo,
    limit,
    sortField,
    sortOrder,
  }) => {
    // 计算需要跳过的记录数
    const skip = (pageNo - 1) * limit;

    // 构建模糊查询的正则表达式(根据用户名（username）进行模糊查询)
    const searchRegex = new RegExp(searchValue, "i"); // 'i' 表示不区分大小写

    // 查询数据库，并只选择需要的字段
    const records = await UserModel.find({ username: searchRegex })
      .select("-password") // 排除密码字段，返回其他所有字段
      .sort({ [sortField]: sortOrder })
      .skip(skip)
      .limit(limit);

    // 计算总记录数（无需根据条件计算的总页数）
    // const total = await UserModel.countDocuments({});
    // 计算基于搜索条件的总记录数
    const total = await UserModel.countDocuments({ username: searchRegex });
    // 或者使用 find().countDocuments()（取决于 Mongoose 版本和偏好）
    // const total = await UserModel.find({ username: searchRegex }).countDocuments();

    // 计算总页数
    const pages = Math.ceil(total / limit);

    return {
      records,
      total,
      pages,
    };
  },

  deleteListItem: async ({ _id }) => {
    return UserModel.deleteOne({ _id });
  },

  putList: async (body) => {
    return UserModel.updateOne({ _id: body._id }, body);
  },
};

module.exports = UserService;
